<template>
  <input
    class="ipt"
    @input="getValue"
    :class="{
      success: state === 'success',
      error: state === 'error',
    }"
    @blur="blurFn"
  />
</template>

<script>
export default {
  data() {
    return {
      state: "",
    };
  },
  props: {
    rules: RegExp,
    msg: {
      type: String,
      //   如果不传msg参数，则默认为 msg = "输入的数据不合法"
      default: "输入的数据不合法",
    },
  },
  methods: {
    getValue(e) {
      this.$emit("input", e.target.value);
    },
    // 失去焦点
    blurFn(e) {
      //   如果正则表达式存在时
      if (this.rules) {
        const str = e.target.value.trim();
        //   校验输入的内容
        if (this.rules.test(str)) {
          this.state = "success";
          console.log(this.rules, str, "校验通过");
        } else {
          this.state = "error";
          this.$notify({ type: "warning", message: this.msg, duration: 1000 });
          console.log(this.rules, str, "校验失败", this.msg);
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.ipt {
  width: 318px;
  height: 48px;
  font-size: 20px;
  border: none;
  outline: none;
  border-bottom: 2px solid #ccc;
  margin: 20px auto;
  display: block;
  background-color: transparent;
}
.success {
  border-bottom: 2px solid green;
}
.error {
  color: red;
  border-bottom: 2px solid red;
}
</style>
